# coding=utf-8
"""
作者：董新强 
创建时间：
描述：
"""
from datetime import datetime, timedelta
import time as timepy

def get_len(obj):
    '''
    获取对象长度
    '''
    if not obj:
        return 0

    try:
        if isinstance(obj, (int, float)):
            return len(str(obj).replace('.', '').replace('-', ''))
        return len(obj)
    except:
        return 0
def to_datetime(time_string, add_day=0):
    '''
    将字符串转换为时间
    :param time_string: 时间字符串
    :param add_day: >0表示向后几天,小于零表示提前几天.
    :return: datetime
    '''

    def convert(time_string):
        if not time_string:
            return None

        if isinstance(time_string, datetime):
            return time_string

        try:
            if isinstance(time_string, str):
                if time_string.find(r'/') > -1:
                    time_string = time_string.replace(r'/', '-')

                if (get_len(time_string) > 10):
                    timeArray = datetime.strptime(time_string, "%Y-%m-%d %H:%M:%S")
                else:
                    timeArray = datetime.strptime(time_string, "%Y-%m-%d")
                return timeArray

            # 时间戳转为时间
            if isinstance(time_string, int):
                date_array = datetime.fromtimestamp(time_string)
                return date_array.strftime("%Y-%m-%d %H:%M:%S")

            return datetime.now()
        except:
            return None

    dtm = convert(time_string)
    if not dtm or not add_day:
        return dtm
    return dtm + timedelta(days=add_day)

def to_timestamp(str_or_datetime):
    '''
    将时间或者时间字符串转换为时间戳
    :param str_or_datetime:
    :type str_or_datetime:
    :return: int or None
    :rtype: int or None
    '''
    try:
        if isinstance(str_or_datetime, int):
            return str_or_datetime

        if not str_or_datetime:
            return 0

        '''
        datetime->timestamp
        '''
        if isinstance(str_or_datetime, datetime):
            return int(str_or_datetime.timestamp())

        '''
        timeArray->timestamp
        '''
        if isinstance(str_or_datetime, timepy.struct_time):
            return int(timepy.mktime(str_or_datetime))

        '''
        string->timestamp
        '''
        if isinstance(str_or_datetime, str):
            if (get_len(str_or_datetime) > 10):
                timeArray = timepy.strptime(str_or_datetime, "%Y-%m-%d %H:%M:%S")
            else:
                timeArray = timepy.strptime(str_or_datetime, "%Y-%m-%d")
            return int(timepy.mktime(timeArray))

        timeArray = timepy.strptime(str(str_or_datetime), "%Y-%m-%d")
        return int(timepy.mktime(timeArray))
    except:
        return 0
